<?php namespace Home\Model;

use Framework\Model\Model;

class User extends Model{

	protected $table = 'user';

	//注册
	public function reg()
	{
		// p($_POST);
		// $obj = new Db('user');

		if(empty($_POST['username']))
		{
			$this->error = '用户名不能为空';
			return false;
		}
		if(empty($_POST['password']))
		{
			$this->error = '密码不能为空';
			return false;
		}

		if($_POST['password']!=$_POST['passworded'])
		{
			$this->error = '密码不一致';
			return false;
		}

		if(strtoupper($_POST['code'])!=$_SESSION['code'])
		{
			$this->error = '验证码输入错误';
			return false;
		}
		if($this->where("username='{$_POST['username']}'")->select())
		{
			$this->error = '用户已存在';
			return false;
		}

		$token = substr(md5(time()),0,10);
		$password = md5($_POST['password'].$token);

		$sql = "insert into user set username=?, password=?, token=?";
		$data = [$_POST['username'],$password,$token];
		$_SESSION['username']=$_POST['username'];
		$this->execute($sql,$data);


		$id = $this->getInsertId();
		$_SESSION['id']=$id;
		return true;
	}

	//登录
	public function login()
	{
		if(empty($_POST['username']))
		{
			$this->error = '用户名不能为空';
			return false;
		}
		if(empty($_POST['password']))
		{
			$this->error = '密码不能为空';
			return false;
		}
		if(!$user = $this->where("username='{$_POST['username']}'")->first())
		{
			$this->error = '帐号不存在';
			return false;
		}

		if(md5($_POST['password'].$user['token'])!=$user['password'])
		{
			$this->error ='密码错误';
			return false;
		}

		$_SESSION['id']=$user['id'];
		$_SESSION['username']=$user['username'];
		return true;
	}























}